import { DynamicModule, Global, Logger, Module } from "@nestjs/common";
import { PostgresqlPersistence } from "y-postgresql";
import { setPersistence } from "./utils";
import { IWSSharedDoc } from "./interfaces";
import * as Y from "yjs";

@Global()
@Module({})
export class YjsPostgresqlModule {
  static forRoot(): DynamicModule {
    return {
      module: YjsPostgresqlModule,
      providers: [
        {
          provide: "YJS_POSTGRESQL_ADAPTER",
          useFactory: async () => {
            Logger.log("YjsPostgresqlAdapter initialized");
            // 返回pg实例
            const pg = await PostgresqlPersistence.build(
              {
                host: "localhost",
                port: 5432,
                database: "postgres",
                user: "postgres",
                password: "123456"
              },
              { tableName: "yjs-writings", useIndex: false, flushSize: 200 }
            );

            setPersistence({
              // 绑定文档状态：用于首次连接时同步数据库状态到内存文档中
              bindState: async (docName: string, ydoc: IWSSharedDoc) => {
                const persistedYdoc = await pg.getYDoc(docName);
                const newUpdates = Y.encodeStateAsUpdate(ydoc);
                pg.storeUpdate(docName, newUpdates);
                Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(persistedYdoc));

                ydoc.on("update", async (update: Uint8Array) => {
                  pg.storeUpdate(docName, update);
                });
              },

              writeState: (docName: string, ydoc: IWSSharedDoc) => {
                return new Promise(resolve => {
                  resolve(true);
                });
              }
            });
            return pg;
          }
        }
      ],
      exports: ["YJS_POSTGRESQL_ADAPTER"]
    };
  }
}
